package com.lujianing.cmd;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Component
@Scope("prototype")
public class Abs {
	// private String resultstr;
	private static final Logger logger= LoggerFactory.getLogger(Abs.class);

	public CmdConsolePrintVo testWayByAbs(String requests,String concurrency,String url) {
		logger.info("requests:{},concurrency:{},url:{}",requests,concurrency,url);
		String path = "D:\\soft\\Apache24\\bin";
//		String path = "D:\\Apache24\\bin";
		String cmd = "cmd /C abs -n 300 -c 100 https://www.baidu.com/ >>abc.txt";
		// String[] cmd2 = new String[]{"com.lujianing.cmd", "/C", "abs", "-n", "300", "-c", "100",
		// "https://www.baidu.com/", ">>abc.txt"};
		String[] cmd2 = new String[] {"cmd", "/C", "abs", "-n",requests, "-c", concurrency, url};
		CmdConsolePrintVo cmdConsolePrintVo = new CmdConsolePrintVo();
		try {
			long startTime=System.currentTimeMillis();
			Process process = Runtime.getRuntime().exec(cmd2, null, new File(path));
			process.waitFor();
			InputStream inputStream = process.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "gb2312"));
			long endTime=System.currentTimeMillis();
			float excTimeMs=endTime-startTime;
			float excTimeS=(float)(excTimeMs)/1000;
			logger.info("执行时间：{} ms {} s",excTimeMs,excTimeS);
			String line = null;
			while ((line = br.readLine()) != null) {
				logger.info(line);
//				logger.info("执行时间：{} ms {} s",excTimeMs,excTimeS);
				matchingCmdConsolePrint(line, cmdConsolePrintVo);
			}
			cmdConsolePrintVo.setExecuteTimeMillisecond(excTimeMs);
			cmdConsolePrintVo.setExecuteTimeSecond(excTimeS);
//			process.destroy();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {

		}
		return cmdConsolePrintVo;
		// }
	}

	public AbsModel interfaceJson(final CmdConsolePrintVo cmdConsolePrintVo) {
		AbsModel absModel = new AbsModel();

		absModel.setServerSoftware(cmdConsolePrintVo.getStrServerSoftware());
		absModel.setServerHostname(cmdConsolePrintVo.getStrServerHostname());
		logger.error(cmdConsolePrintVo.getStrServerPort());
		absModel.setServerPort(Integer.parseInt(cmdConsolePrintVo.getStrServerPort()));
		absModel.setsSLTLSProtocol(cmdConsolePrintVo.getStrSSLTLSProtocol());
		absModel.setServerTempKey(cmdConsolePrintVo.getStrServerTempKey());
		absModel.settLSServerName(cmdConsolePrintVo.getStrTLSServerName());
		absModel.setDocumentPath(cmdConsolePrintVo.getStrDocumentPath());
		absModel.setDocumentLength(cmdConsolePrintVo.getStrDocumentLength());
		absModel.setConcurrencyLevel(cmdConsolePrintVo.getStrConcurrencyLevel());
		absModel.setTimeTakenForTests(cmdConsolePrintVo.getStrTimeTakenForTests());

		absModel.setCompleteRequests(Double.parseDouble(cmdConsolePrintVo.getStrCompleteRequests()));

		absModel.setFailedRequests(Double.parseDouble(cmdConsolePrintVo.getStrFailedRequests()));

		
		absModel.setTotalTransferred(Double.parseDouble(splitAndRemoveUnit(cmdConsolePrintVo.getStrTotalTransferred())));

		absModel.sethTMLTransferred(Double.parseDouble(splitAndRemoveUnit(cmdConsolePrintVo.getStrHTMLTransferred())));

		absModel.setRequestsPerSecond(Double.parseDouble(splitAndRemoveUnit(cmdConsolePrintVo.getStrRequestsPerSecond())));

		absModel.setTimePerRequest(Double.parseDouble(splitAndRemoveUnit(cmdConsolePrintVo.getStrTimePerRequest())));

		absModel.setTimePerRequestAcrossAllConcurrentRequests(
				Double.parseDouble(splitAndRemoveUnit(cmdConsolePrintVo.getStrTimePerRequestAcrossAllConcurrentRequests())));

		absModel.setTransferRate(Double.parseDouble(splitAndRemoveUnit(cmdConsolePrintVo.getStrTransferRate())));

		absModel.setConnect(createConnectionTimesModel(cmdConsolePrintVo.getStrConnect()));
		absModel.setProcessing(createConnectionTimesModel(cmdConsolePrintVo.getStrProcessing()));
		absModel.setWaiting(createConnectionTimesModel(cmdConsolePrintVo.getStrWaiting()));
		absModel.setTotal(createConnectionTimesModel(cmdConsolePrintVo.getStrTotal()));
		return absModel;

	}

	private static ConnectionTimesModel createConnectionTimesModel(String strConnect) {
		double[] temp = splitAndDouble(strConnect);
		ConnectionTimesModel connectionTimesModel = new ConnectionTimesModel();
		connectionTimesModel.setMin(temp[0]);
		connectionTimesModel.setMean(temp[1]);
		connectionTimesModel.setSd(temp[2]);
		connectionTimesModel.setMedian(temp[3]);
		connectionTimesModel.setMax(temp[4]);
		return connectionTimesModel;
	}

	private static double[] splitAndDouble(String strConnect) {

		String[] temp = split(strConnect);
		double[] tempDouble = new double[temp.length];
		for (int i = 0; i < temp.length; i++) {
			tempDouble[i] = Double.parseDouble(temp[i]);
		}
		return tempDouble;
	}
	
	private static String splitAndRemoveUnit(String strConnect) {
		return split(strConnect)[0];
	}
	private static String[] split(String strConnect) {
		return strConnect.split("\\s+");
	}
	
	

	private static CmdConsolePrintVo matchingCmdConsolePrint(String line, final CmdConsolePrintVo cmdConsolePrintVo) {

		if (line.contains(AbsEnum.ServerSoftware.getName())) {
			String strServerSoftware = line.substring(AbsEnum.ServerSoftware.getLength()).trim();
			cmdConsolePrintVo.setStrServerSoftware(strServerSoftware.trim());
		}
		if (line.contains(AbsEnum.ServerHostname.getName())) {
			String strServerHostname = line.substring(AbsEnum.ServerHostname.getLength()).trim();
			cmdConsolePrintVo.setStrServerHostname(strServerHostname.trim());
		}
		if (line.contains(AbsEnum.ServerPort.getName())) {
			String strServerPort = line.substring(AbsEnum.ServerPort.getLength()).trim();
			logger.error(strServerPort.trim());
			cmdConsolePrintVo.setStrServerPort(strServerPort.trim());
		}
		if (line.contains(AbsEnum.SSLTLSProtocol.getName())) {
			String strSSLTLSProtocol = line.substring(AbsEnum.SSLTLSProtocol.getLength()).trim();
			cmdConsolePrintVo.setStrSSLTLSProtocol(strSSLTLSProtocol.trim());
		}
		if (line.contains(AbsEnum.ServerTempKey.getName())) {
			String strServerTempKey = line.substring(AbsEnum.ServerTempKey.getLength()).trim();
			cmdConsolePrintVo.setStrServerTempKey(strServerTempKey.trim());
		}
		if (line.contains(AbsEnum.TLSServerName.getName())) {
			String strTLSServerName = line.substring(AbsEnum.TLSServerName.getLength()).trim();
			cmdConsolePrintVo.setStrTLSServerName(strTLSServerName.trim());
		}
		if (line.contains(AbsEnum.DocumentPath.getName())) {
			String strDocumentPath = line.substring(AbsEnum.DocumentPath.getLength()).trim();
			cmdConsolePrintVo.setStrDocumentPath(strDocumentPath.trim());
		}
		if (line.contains(AbsEnum.DocumentLength.getName())) {
			String strDocumentLength = line.substring(AbsEnum.DocumentLength.getLength()).trim();
			cmdConsolePrintVo.setStrDocumentLength(strDocumentLength.trim());
		}

		if (line.contains(AbsEnum.ConcurrencyLevel.getName())) {
			String strConcurrencyLevel = line.substring(AbsEnum.ConcurrencyLevel.getLength()).trim();
			cmdConsolePrintVo.setStrConcurrencyLevel(strConcurrencyLevel.trim());
		}

		if (line.contains(AbsEnum.TimeTakenForTests.getName())) {
			String strTimeTakenForTests = line.substring(AbsEnum.TimeTakenForTests.getLength()).trim();
			cmdConsolePrintVo.setStrTimeTakenForTests(strTimeTakenForTests.trim());
		}

		if (line.contains(AbsEnum.CompleteRequests.getName())) {
			String strCompleteRequests = line.substring(AbsEnum.CompleteRequests.getLength()).trim();
			cmdConsolePrintVo.setStrCompleteRequests(strCompleteRequests.trim());
		}

		if (line.contains(AbsEnum.FailedRequests.getName())) {
			String strFailedRequests = line.substring(AbsEnum.FailedRequests.getLength()).trim();
			cmdConsolePrintVo.setStrFailedRequests(strFailedRequests.trim());
		}

		if (line.contains(AbsEnum.TotalTransferred.getName())) {
			String strTotalTransferred = line.substring(AbsEnum.TotalTransferred.getLength()).trim();
			cmdConsolePrintVo.setStrTotalTransferred(strTotalTransferred.trim());
		}

		if (line.contains(AbsEnum.HTMLTransferred.getName())) {
			String strHTMLTransferred = line.substring(AbsEnum.HTMLTransferred.getLength()).trim();
			cmdConsolePrintVo.setStrHTMLTransferred(strHTMLTransferred.trim());
		}

		if (line.contains(AbsEnum.RequestsPerSecond.getName())) {
			String strRequestsPerSecond = line.substring(AbsEnum.RequestsPerSecond.getLength()).trim();
			cmdConsolePrintVo.setStrRequestsPerSecond(strRequestsPerSecond.trim());
		}

		if (line.contains(AbsEnum.TimePerRequest.getName())) {
			
			if(!line.endsWith("requests)")) {
				String strTimePerRequest = line.substring(AbsEnum.TimePerRequest.getLength()).trim();
				cmdConsolePrintVo.setStrTimePerRequest(strTimePerRequest.trim());
			}else {
				String strTimePerRequestAcrossAllConcurrentRequests = line.substring(AbsEnum.TimePerRequest.getLength()).trim();
				cmdConsolePrintVo.setStrTimePerRequestAcrossAllConcurrentRequests(strTimePerRequestAcrossAllConcurrentRequests.trim());
			}
		} 

		if (line.contains(AbsEnum.TransferRate.getName())) {
			String strTransferRate = line.substring(AbsEnum.TransferRate.getLength()).trim();
			cmdConsolePrintVo.setStrTransferRate(strTransferRate.trim());
		}
		if (line.contains(AbsEnum.Connect.getName())) {
			String strConnect = line.substring(AbsEnum.Connect.getLength()).trim();
			cmdConsolePrintVo.setStrConnect(strConnect.trim());
		}
		if (line.contains(AbsEnum.Processing.getName())) {
			String strProcessing = line.substring(AbsEnum.Processing.getLength()).trim();
			cmdConsolePrintVo.setStrProcessing(strProcessing.trim());
		}
		if (line.contains(AbsEnum.Waiting.getName())) {
			String strWaiting = line.substring(AbsEnum.Waiting.getLength()).trim();
			cmdConsolePrintVo.setStrWaiting(strWaiting.trim());
		}
		if (line.contains(AbsEnum.Total.getName())) {
			String strTotal = line.substring(AbsEnum.Total.getLength()).trim();
			cmdConsolePrintVo.setStrTotal(strTotal.trim());
		}
		return cmdConsolePrintVo;

	}
	// public static void methodTwo() {
	// try {
	// String result = new ProcessExecutor().command("com.lujianing.cmd", "/C",
	// "D:\\softInstall\\wamp2016_new\\bin\\apache\\apache2.4.9\\bin\\abs", "-n
	// 300", "-c 100", "https://www.baidu.com/",
	// ">>D:\\softInstall\\wamp2016_new\\bin\\apache\\apache2.4.9\\bin\\aa.txt")
	// .timeout(60, TimeUnit.SECONDS)
	// .readOutput(true).execute()
	// .outputUTF8();
	// System.out.println(result);
	// } catch (IOException e) {
	// e.printStackTrace();
	// } catch (InterruptedException e) {
	// e.printStackTrace();
	// } catch (TimeoutException e) {
	// e.printStackTrace();
	// }
	// }
	// public static void methodOne() {
	// String path;
	// if (HostUtils.isWindows()) {
	// path = "D:\\softInstall\\wamp2016_new\\bin\\apache\\apache2.4.9\\bin\\";
	// String com.lujianing.cmd = "com.lujianing.cmd /C abs -n 300 -c 100 https://www.baidu.com/ >>abc.txt";
	// String[] cmd2 = new String[]{"com.lujianing.cmd", "/C", "abs", "-n", "300", "-c", "100",
	// "https://www.baidu.com/", ">>abc.txt"};
	// try {
	// Process process = Runtime.getRuntime().exec(cmd2, null, new File(path));
	// process.waitFor();
	// InputStream inputStream = process.getInputStream();
	// BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,
	// "gb2312"));
	// String line = null;
	// while ((line = br.readLine()) != null) {
	// System.out.println(line);
	// }
	// } catch (IOException e) {
	// e.printStackTrace();
	// } catch (InterruptedException e) {
	// e.printStackTrace();
	// }
	//
	// }
	// }

	public static void main(String[] args) {
		Abs abs=new Abs();
		System.out.println("--------------");
		System.out.println(AbsEnum.ServerTempKey.name());
		System.out.println(AbsEnum.ServerTempKey.getName());
		System.out.println(AbsEnum.ServerTempKey.getLength());
		
		String requests="300";
		String concurrency="300";
		String url="https://www.baidu.com/";
		CmdConsolePrintVo cmdConsolePrintVo=abs.testWayByAbs(requests,concurrency,url);
		
		
//		String[] counts=new String[] {"500","1000","1500"};
		String[] counts=new String[] {"100"};
		
		List<CmdConsolePrintVo> cmdConsolePrintVoList=new ArrayList<>();
		for (int i = 0; i < counts.length; i++) {
			cmdConsolePrintVoList.add(abs.testWayByAbs(counts[i],concurrency,url));
		}
//		List<AbsModel> absModelList=new ArrayList<>();
//		for (int i = 0; i < cmdConsolePrintVoList.size(); i++) {
//			AbsModel absModel = interfaceJson(cmdConsolePrintVo);
//			System.out.println(absModel);
//			absModelList.add(absModel);
//		}
//		ChartsData chartsData = interfaceEcharts(absModelList);
//		return interfaceJson(cmdConsolePrintVo);

	}

	public static ChartsData interfaceEcharts(List<AbsModel> absModelList) {
		ChartsData chartsData=new ChartsData();
		ChartsConnectionTimes connect=new ChartsConnectionTimes();
		ChartsConnectionTimes processing=new ChartsConnectionTimes();
		ChartsConnectionTimes waiting=new ChartsConnectionTimes();
		ChartsConnectionTimes total=new ChartsConnectionTimes();
		double[] connectsMin=new double[absModelList.size()];
		double[] connectsMean=new double[absModelList.size()];
		double[] connectsMedian=new double[absModelList.size()];
		double[] connectsMax=new double[absModelList.size()];
		double[] processingsMin=new double[absModelList.size()];
		double[] processingsMean=new double[absModelList.size()];
		double[] processingsMedian=new double[absModelList.size()];
		double[] processingsMax=new double[absModelList.size()];
		double[] waitingsMin=new double[absModelList.size()];
		double[] waitingsMean=new double[absModelList.size()];
		double[] waitingsMedian=new double[absModelList.size()];
		double[] waitingsMax=new double[absModelList.size()];
		
		double[] totalsMin=new double[absModelList.size()];
		double[] totalsMean=new double[absModelList.size()];
		double[] totalsMedian=new double[absModelList.size()];
		double[] totalsMax=new double[absModelList.size()];
		for (int i = 0; i < absModelList.size(); i++) {
			AbsModel absModel = absModelList.get(i);
			
			connectsMin[i]=absModel.getConnect().getMin();
			connectsMean[i]=absModel.getConnect().getMean();
			connectsMedian[i]=absModel.getConnect().getMedian();
			connectsMax[i]=absModel.getConnect().getMax();
			
			processingsMin[i]=absModel.getProcessing().getMin();
			processingsMean[i]=absModel.getProcessing().getMean();
			processingsMedian[i]=absModel.getProcessing().getMedian();
			processingsMax[i]=absModel.getProcessing().getMax();
			
			waitingsMin[i]=absModel.getWaiting().getMin();
			waitingsMean[i]=absModel.getWaiting().getMean();
			waitingsMedian[i]=absModel.getWaiting().getMedian();
			waitingsMax[i]=absModel.getWaiting().getMax();
			
			totalsMin[i]=absModel.getTotal().getMin();
			totalsMean[i]=absModel.getTotal().getMean();
			totalsMedian[i]=absModel.getTotal().getMedian();
			totalsMax[i]=absModel.getTotal().getMax();
			 
		}
		connect.setMin(connectsMin);
		connect.setMean(connectsMean);
		connect.setMedian(connectsMedian);
		connect.setMax(connectsMax);
		// TODO Auto-generated method stub
		processing.setMin(processingsMin);
		processing.setMean(processingsMean);
		processing.setMedian(processingsMedian);
		processing.setMax(processingsMax);
		waiting.setMin(waitingsMin);
		waiting.setMean(waitingsMean);
		waiting.setMedian(waitingsMedian);
		waiting.setMax(waitingsMax);
		total.setMin(totalsMin);
		total.setMean(totalsMean);
		total.setMedian(totalsMedian);
		total.setMax(totalsMax);
		
		chartsData.setConnect(connect);
		chartsData.setProcessing(processing);
		chartsData.setWaiting(waiting);
		chartsData.setTotal(total);
		return chartsData;
	}

	public static String getbackage(String path) {
		Process p;
		// test.bat中的命令是ipconfig/all
		String cmd = "aapt dump badging " + path;
		// String com.lujianing.cmd="jarsigner -verify -verbose -certs
		// C:\\Users\\Administrator\\Desktop\\PandaClient.apk";
		String resultstr = null;
		try {
			// 执行命令
			p = Runtime.getRuntime().exec(cmd);
			// 取得命令结果的输出流
			InputStream fis = p.getInputStream();
			// 用一个读输出流类去读
			// 用缓冲器读行
			BufferedReader br = new BufferedReader(new InputStreamReader(fis, "GB2312"));
			String line = null;
			// 直到读完为止
			int i = 0;
			while ((line = br.readLine()) != null) {
				if (line.contains("package:")) { // 解析符合自己需要的內容，获取之后，直接返回。

					resultstr = line;
					break;
				}
				// resultstr=line;
				i++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resultstr;
	}
}
